<template>
  <div class="app-container">
    <template>
      <el-row>
        <el-col :span="24">
          <div class="h_top">
            <div class="search_box">
              <el-form :model="query" :inline="true">
                <el-row :gutter="10">
                  <el-col :xl="3" :lg="5" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">编 号</div>
                      <el-input v-model="query.coding" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="5" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">名 称</div>
                      <el-input v-model="query.name" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="2" :md="2" :sm="2">
                    <el-form-item>
                      <div class="search_label">操 作</div>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="search">查找</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="toolBars">
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-document-add" size="mini" @click="addHandler()">新增</el-button>
              </div>
              <div class="buttonBox">
                <el-upload :show-file-list="false" action="" :before-upload="workbook">
                  <el-button type="primary" size="mini" icon="el-icon-upload">批量新增</el-button>
                </el-upload>
              </div>
              <div class="buttonBox">
                <el-upload :show-file-list="false" action="" :before-upload="workbookUpdate">
                  <el-button type="primary" size="mini" icon="el-icon-upload">批量更新</el-button>
                </el-upload>
              </div>
              <div class="buttonBox">
                <a class="download" href="https://beiqi.aiemtc.com/exl/knowledge.xlsx" download="" title="下载"><el-button type="primary" icon="el-icon-download" size="mini">下载模板</el-button></a>
              </div>
              <div class="buttonBox" :hidden="!canButton">
                <el-button type="primary" icon="el-icon-delete" :disabled="!selection.length" size="mini" @click="remove">删除</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="reloadHandler">刷新</el-button>
              </div>
              <div class="fr">总数：<span>{{ total }}</span></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <div>
      <el-row :gutter="10">
        <el-col :xl="4" :lg="5" :md="7" :sm="8">
          <div class="h100vh">
            <el-tabs type="border-card" :style="leftHeight" :stretch="true">
              <el-tab-pane label="按分类">
                <el-input v-model="filterCategoryText" placeholder="输入关键字进行过滤" size="mini" />
                <div class="overflow" :style="treeHeight">
                  <el-tree ref="categoryTree" class="filter-tree" :data="CategoryTree" :props="defaultProps" accordion :default-expand-all="false" :filter-node-method="filterCategoryNode" :expand-on-click-node="false" @node-click="CategoryClick" />
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
        <el-col :xl="20" :lg="19" :md="17" :sm="16">
          <el-table v-loading="loading" :data="knowledgeList" size="small" stripe border :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%" :height="tableMaxHeight" @selection-change="selectionHandler">
            <el-table-column type="index" width="50" label="序号" align="center" />
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="coding" label="编号" min-width="25%" align="center" />
            <el-table-column prop="name" label="名称" min-width="25%" />
            <el-table-column prop="format" label="格式" min-width="25%" align="center" :formatter="knowledgeFormat" />
            <el-table-column prop="cr_admin.name" label="创建人" min-width="25%" align="center" />
            <el-table-column prop="create_time" label="创建时间" width="200" align="center" />
            <el-table-column v-if="listHandle" fixed="right" label="操作" width="200" align="center">
              <template scope="scope">
                <el-button type="primary" size="mini" @click="updateHandler(scope.row.id)">编辑</el-button>
                <div style="display: inline-block" class="ml10"><div :hidden=!canButton><el-button size="mini" type="danger" @click="confirmDel(scope.row.id)">删除</el-button></div></div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination class="page" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import API from '@/api/knowledge/knowledge'
import xlsx from 'xlsx'
import { mapGetters } from 'vuex'
export default {
  inject: ['reload', 'goUrl', 'delOne', 'delMany', 'getScope'],
  data() {
    return {
      loading: false,
      filterCategoryText: '',
      CategoryTree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      knowledgeList: [],
      total: 0,
      query: { page: 1, limit: 15 },
      selection: [],
      leftHeight: null,
      treeHeight: null,
      canButton: false
    }
  },
  computed: {
    tableMaxHeight() {
      return window.innerHeight - 260 + 'px'
    },
    treeMaxHeight() {
      return window.innerHeight - 360 + 'px'
    },
    listHandle() {
      return this.$store.state.settings.listHandle
    },
    ...mapGetters([
      'userId'
    ])
  },
  watch: {
    filterCategoryText(val) {
      this.$refs.categoryTree.filter(val)
    }
  },
  created() {
    if (this.getScope(this.userId) === 1) {
      this.canButton = true
    }
    this.leftHeight = { 'height': this.tableMaxHeight }
    this.treeHeight = { 'height': this.treeMaxHeight }
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
    this.tree()
  },
  methods: {
    search() {
      this.query.page = 1
      this.index()
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    filterCategoryNode(value, CategoryTree) {
      if (!value) return true
      return CategoryTree.name.indexOf(value) !== -1
    },
    index() {
      this.loading = true
      API.knowledgeList(this.query).then(response => {
        this.total = response.data.total
        this.knowledgeList = response.data.data
      }).finally(() => {
        this.loading = false
      })
    },
    remove() {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const selection = this.selection
      this.delMany(API, selection)
    },
    confirmDel(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      this.delOne(API, id, false)
    },
    tree() {
      API.categoryTree().then(response => {
        this.CategoryTree = response.data
      })
    },
    CategoryClick(v) {
      this.query.category_id = v.id
      this.query.category_name = v.name
      this.index()
    },
    addHandler() {
      const category_id = this.query.category_id
      const category_name = this.query.category_name
      if (category_id) {
        this.goUrl(`/knowledge/knowledge/knowledge_add?category=${category_id}&name=${category_name}`)
      } else {
        this.$message.error('请先选择分类')
      }
    },
    updateHandler(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const url = `/knowledge/knowledge/knowledge_edit/${id}`
      this.goUrl(url)
    },
    reloadHandler() {
      this.reload()
    },
    workbook(file) {
      const reader = new FileReader()
      const _this = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = xlsx.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        API.excel(outData).then(response => {
          if (response.data.error_code === 1) {
            _this.$message.success('恭喜你，导入成功')
            _this.reload()
          } else {
            _this.$message.error(response.data.message)
          }
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    workbookUpdate(file) {
      const reader = new FileReader()
      const _this = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = xlsx.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        API.excelUpdate(outData).then(response => {
          if (response.data.error_code === 1) {
            _this.$message.success('恭喜你，更新成功')
            _this.reload()
          } else {
            _this.$message.error(response.data.message)
          }
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    knowledgeFormat(row) {
      if (row.format === 0) {
        return 'jpg'
      } else if (row.format === 1) {
        return 'png'
      } else if (row.format === 2) {
        return 'gif'
      } else if (row.format === 3) {
        return 'doc'
      } else if (row.format === 4) {
        return 'xls'
      } else if (row.format === 5) {
        return 'ppt'
      } else if (row.format === 6) {
        return 'pdf'
      } else if (row.format === 7) {
        return 'mp4'
      }
    }
  }
}
</script>
<style>
.filter-tree{
  margin-top: 10px;
}
.overflow{
  overflow-y: auto;
  margin-top: 10px;
}
</style>
